Macro Expansion

Macros provide a way to extend the syntax of Lisp. A macro function is applied to its unevaluated arguments. Its parent contour is the global contour. The result returned by a macro function is a Lisp expression which is then evaluated in the lexical context where the macro call appeared. As with the duality between EVAL and APPLY, it is often hard to teach beginners how macros work, but evaltrace notation can be used to show macros in action. Consider the SIMPLE-INCF macro, a simplified version of Common Lisp's INCF:


\begin{code}
(defmacro simple-incf (var)
(print a)
(list 'setq var (list '+ var 1)))
\strut
(setf a 'foo)
\strut
(defun test (a)
(simple-incf a))
\end{code}

An evaltrace of this macro is shown below. Note that the symbol A appearing in the body of the macro is taken as a reference to the global variable A, because the macro's parent contour is the global contour. But the A appearing in the SETQ expression returned by the macro is evaluated within the lexical context of TEST, and so refers to the local variable A visible in the body of TEST.


\begin{evaltrace}
;the global variable A has value FOO
\strut
+--> ;(test 5)
\ve...
...t ;set local variable A to 6
* +_-> ;6
+_*> ;Result of TEST is 6
\end{evaltrace}

Macro expansions are drawn with a dotted line. The result of a macro expansion is evaluated normally, as shown by the thin solid line to which the dotted line connects. Notice that the argument to the macro is not evaluated, so the input to SIMPLE-INCF is the symbol A instead of the value 5.